package link.ten_fei.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import link.ten_fei.Bean.Doc_User;
import link.ten_fei.service.UserJdcService;
import link.ten_fei.service.UserJdcServiceImpl;

/**
 * Servlet implementation class UserJdcServlet
 */
@WebServlet("/userJdc.action")
public class UserJdcServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public UserJdcServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#service(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setCharacterEncoding("utf-8");
		request.setCharacterEncoding("utf-8");
		UserJdcService userJdcService = new UserJdcServiceImpl();
		String action = request.getParameter("action");
		// 用户id
		String id = request.getParameter("id");
		if (action == null) {
			// 返回搜索栏内的输入情况
			String doc_name = request.getParameter("doc_name");
			if (doc_name == null || doc_name.equals("")) {
				// 输入框提示值
				request.setAttribute("query_tip", "请输入...");
			} else if (doc_name != null && !doc_name.equals("")) {
				request.setAttribute("query_tip", doc_name);
			}
			// 将根据名字搜索的内容封装在一个集合中
			List<Doc_User> users = userJdcService.find(doc_name, 0);
			// 保存查询结果
			request.setAttribute("users", users);
			request.setAttribute("mainRight", "/WEB-INF/jsp/userJdc.jsp");
			request.getRequestDispatcher("/WEB-INF/jsp/main.jsp").forward(request, response);

		} else if (action != null && action.equals("delete")) {
			response.setCharacterEncoding("utf-8");
			int flag = userJdcService.deleteById(Integer.parseInt(id));
			PrintWriter writer = response.getWriter();
			if (flag == 1) {
				writer.print("删除成功！！！");
			} else if (flag == 0) {
				writer.print("已删除！！！");
			}
		} else if (action != null && action.equals("reset")) {
			response.setCharacterEncoding("utf-8");
			userJdcService.reset(Integer.parseInt(id));
			PrintWriter writer = response.getWriter();
			writer.print("重置成功！！！");

		} else if (action != null && action.equals("modify")) {
			List<Doc_User> users = userJdcService.find(null, Integer.parseInt(id));
			Doc_User user = null;
			// 遍历集合
			// users为储存多个实体类的对象的地址
			// user为单个实体类对象的地址
			for (int i = 0; i < users.size(); i++) {
				user = users.get(i);
			}
			request.setAttribute("user", user);
			request.setAttribute("mainRight", "/WEB-INF/jsp/addUser.jsp");
			request.getRequestDispatcher("/WEB-INF/jsp/main.jsp").forward(request, response);
		}

	}

}
